package cn.lnexin.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class TempFileUtil {
	static Logger logger = LogManager.getLogger(TempFileUtil.class);
	
	public static boolean intiTemp(String tempDir, String tempFileName, List<String> files) {
		File tempdir = new File(tempDir);
		if (!tempdir.exists()) {
			tempdir.mkdirs();
			logger.info("[{}] dir inti success!", tempdir);
		}
		File temp = new File(tempdir + File.separator + tempFileName);
		if (temp.exists()) {
			return true;
		} else {
			try {
				temp.createNewFile();
				logger.info("create {} success!", temp.getPath());
				writeData(temp.getPath(), files, false);
			} catch (IOException e) {
				logger.error("create {} failure! {}", temp.getPath(), e);
			}
			logger.info("first inti complete!");
			return false;
		}
	}
	
	public static void writeData(String tempFilePath, List data, boolean isappend) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(tempFilePath, isappend));
		for (Object object : data) {
			bw.write(object.toString());
			bw.newLine();
		}
		bw.flush();
		bw.close();
		logger.info("{} has be writed {} records!", tempFilePath, data.size());
	}
	
	// 获取老缓存文件中的列表
	public static List<String> readTempList(String tempFileFullName) {
		List<String> templist = new ArrayList<>();
		InputStreamReader in = null;
		try {
			in = new InputStreamReader(new FileInputStream(tempFileFullName), "UTF-8");
			BufferedReader reader = new BufferedReader(in);
			String line = null;
			while ((line = reader.readLine()) != null) {
				templist.add(line);
			}
			reader.close();
		} catch (UnsupportedEncodingException e) {
			logger.error("unsuport Encoding tempfile !{}", e);
		} catch (FileNotFoundException e) {
			logger.error("[{}] is not exists! {}", tempFileFullName, e);
		} catch (IOException e) {
			logger.error("read tempfile faliure! {}", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("inputstream close failure!");
				}
			}
		}
		return templist;
	}
}
